package com.xingkong.behavior.model;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class Converter {
	private JSONObject ja;
	public Converter Converter(){
		return this;
	}
	public void graphConvertToJson(Graph graph){
//		Map<String, ArrayList<HashMap<String, String>>> resultMap=new HashMap<String,ArrayList<HashMap<String, String>>>();
//		ArrayList<HashMap<String, String>> nodeList=new ArrayList<HashMap<String, String>>();
//		ArrayList<HashMap<String, String>> edgeList=new ArrayList<HashMap<String, String>>();
//		for(Vertex vertex:graph.getVertexList()){
//			HashMap<String,String> nodeTempMap=new HashMap<String,String>();
//			
//			nodeTempMap.put("id", vertex.getID()+"");
//			nodeTempMap.put("state", vertex.isActive()?"1":"0");
//			nodeTempMap.put("threshold", vertex.getThreshold()+"");
//			Integer dout=0;
//			for(Vertex inner_vertex:graph.getVertexList()){
//				if(inner_vertex.getInVertexMap().get(vertex.getID())!=null)
//					dout++;
//			}
//			nodeTempMap.put("din", vertex.getInVertexMap().size()+"");
//			nodeTempMap.put("dout", dout+"");
//			nodeTempMap.put("dtotal", (vertex.getInVertexMap().size()+dout)+"");
//			for(Map.Entry<Integer,Double> entry:vertex.getInVertexMap().entrySet()){
//				HashMap<String,String> edgeTempMap=new HashMap<String,String>();
//				edgeTempMap.put("from_id", entry.getKey()+"");
//				edgeTempMap.put("to_id", vertex.getID()+"");
//				edgeTempMap.put("value", entry.getValue()+"");
//				edgeTempMap.put("state", "0");
//				edgeList.add(edgeTempMap);
//			}
//			nodeList.add(nodeTempMap);
//		}
//		resultMap.put("nodes", nodeList);
//		resultMap.put("links", edgeList);
//		ja=JSONObject.fromObject(resultMap);
//		System.out.println(ja);
		int edgesID=0;
		JSONObject resultMap=new JSONObject();
		JSONArray nodeList=new JSONArray();
		JSONArray edgeList=new JSONArray();
		for(Vertex vertex:graph.getVertexList()){
			JSONObject nodeTempMap=new JSONObject();
			
			nodeTempMap.put("id", vertex.getID());
			nodeTempMap.put("x", vertex.getX());
			nodeTempMap.put("y", vertex.getY());
			nodeTempMap.put("size", vertex.getSize());
			nodeTempMap.put("label",vertex.getLabel());
			nodeTempMap.put("state", vertex.isActive()?1:0);
			nodeTempMap.put("threshold", vertex.getThreshold());
			Integer dout=0;
			for(Vertex inner_vertex:graph.getVertexList()){
				if(inner_vertex.getInVertexMap().get(vertex.getID())!=null)
					dout++;
			}
			nodeTempMap.put("din", vertex.getInVertexMap().size());
			nodeTempMap.put("dout", dout);
			nodeTempMap.put("dtotal", vertex.getInVertexMap().size()+dout);
			for(Map.Entry<String,Double> entry:vertex.getInVertexMap().entrySet()){
				JSONObject edgeTempMap=new JSONObject();
				edgeTempMap.put("source", entry.getKey());
				edgeTempMap.put("target", vertex.getID());
				edgeTempMap.put("value", entry.getValue());
				edgeTempMap.put("state", 0);
				edgeTempMap.put("id", (++edgesID)+"");
				edgeList.add(edgeTempMap);
			}
			nodeList.add(nodeTempMap);
		}
		resultMap.put("nodes", nodeList);
		resultMap.put("edges", edgeList);
		ja=resultMap;
		//System.out.println(ja);
	}
	public void printToFile(String filePath){
		if(ja!=null){
			try {
	            File file = new File(filePath);
	            PrintStream ps = new PrintStream(new FileOutputStream(file));
	            ps.println(ja.toString());// 往文件里写入字符串
	            ps.close();
	        } catch (FileNotFoundException e) {
	            e.printStackTrace();
	        }
			System.out.println("输出"+filePath+"成功！");
		}else{
			System.out.println("没有可输出内容");
		}
	}
	public String printResult(){
		return ja.toString();
	}
//	public void reSerializable(String filePath,String serialFilePath){
//		File file=new File(filePath);
//		Long filelength = file.length();     //获取文件长度
//        byte[] filecontent = new byte[filelength.intValue()];
//        try {
//            FileInputStream in = new FileInputStream(file);
//            in.read(filecontent);
//            in.close();
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        
//        writeObject(JSONObject.fromObject(new String(filecontent)),serialFilePath);
//	}
	public Graph readJsonFromFile(String filePath,boolean autoactive,Integer autoactivenumber,Integer [] activeList){
		
		File file=new File(filePath);
		Long filelength = file.length();     //获取文件长度
        byte[] filecontent = new byte[filelength.intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ja=JSONObject.fromObject(new String(filecontent));
//        System.out.println(ja.get("nodes"));
//        System.out.println(ja.get("links"));
        JSONArray nodesArray=JSONArray.fromObject(ja.get("nodes"));
        JSONArray edgesArray=JSONArray.fromObject(ja.get("edges"));
        Graph g=new Graph();
        Map<String,HashMap<String,Double>> nodes_edges_map=new HashMap<String,HashMap<String,Double>>();
        Iterator edgeIt=edgesArray.iterator();
        while(edgeIt.hasNext()){
        	JSONObject tempj=(JSONObject)edgeIt.next();
        	if(nodes_edges_map.get((String) tempj.get("target"))!=null){
        		nodes_edges_map.get((String)tempj.get("target")).put((String)tempj.get("source"), tempj.getDouble("value"));
        	}else{
        		HashMap<String,Double> inVertexMap=new HashMap<String,Double>();
        		inVertexMap.put((String)tempj.get("source"),tempj.getDouble("value"));
        		nodes_edges_map.put((String)tempj.get("target"), inVertexMap);
        	}
        }
        boolean anyActive=false;
        Iterator it=nodesArray.iterator();
        while(it.hasNext()){
        	JSONObject tempj=(JSONObject)it.next();
        	Double threshold=Math.random();
        	if(tempj.get("threshold")!=null) threshold=(Double)tempj.get("threshold");
        	Vertex vertex=new Vertex((String)tempj.get("id"),tempj.getDouble("x"),tempj.getDouble("y"),tempj.getDouble("size"),(String)tempj.get("label"),threshold);
        	if(((Integer)tempj.get("state")).equals(1)) anyActive=true;
        	vertex.setActive(((Integer)tempj.get("state")).equals(1)?true:false);
        	if(nodes_edges_map.get(vertex.getID())!=null)
        		vertex.getInVertexMap().putAll(nodes_edges_map.get(vertex.getID()));
        	g.getVertexList().add(vertex);
        }
       
        if(autoactive){
        	for(int i=0;i<autoactivenumber;i++){
            	Random r = new Random();
            	int activeVertexIndex=Math.abs(r.nextInt() % g.getVertexList().size());
            	g.getVertexList().get(activeVertexIndex).setActive(true);
            	System.out.println("初始化激活的节点："+g.getVertexList().get(activeVertexIndex).getID());
        	}
        }else if(activeList!=null&&activeList.length>0){
        	for(Integer activeVertexIndex:activeList){
        		g.getVertexList().get(activeVertexIndex).setActive(true);
            	System.out.println("初始化激活的节点："+g.getVertexList().get(activeVertexIndex).getID());
        	}
        }else{
        	 if(!anyActive){
        		System.out.println("没有任何节点被激活！");
             	for(int i=0;i<50;i++){
             	Random r = new Random();
             	int activeVertexIndex=Math.abs(r.nextInt() % g.getVertexList().size());
             	g.getVertexList().get(activeVertexIndex).setActive(true);
             	System.out.println("初始化激活的节点："+g.getVertexList().get(activeVertexIndex).getID());
             	}
             }
        }
//        System.out.println("读取文件后的节点信息");
//        System.out.println(g.getVertexList());
        return g;//返回文件内容,默认编码
	}
	private static void writeObject(Object obj, String filePath)
	{
	    try
	    {
	        FileOutputStream fos = new FileOutputStream(filePath);
	        ObjectOutputStream os = new ObjectOutputStream(fos);
	        os.writeObject(obj);
	        os.flush();
	        fos.flush();
	        os.close();
	        fos.close();
	        System.out.println("序列化成功。");
	    }
	    catch(Exception ex)
	    {
	        ex.printStackTrace();
	    }
	}

	private static Object readObject(String filePath)
	{
	    try
	    {
	        FileInputStream fis = new FileInputStream(filePath);
	        ObjectInputStream is = new ObjectInputStream(fis);
	        
	        Object temp = is.readObject();
	        
	        fis.close();
	        is.close();
	        
	        if (temp != null)
	        {
	            System.out.println("反序列化成功。");
	            return temp;
	        }
	    }
	    catch(Exception ex)
	    {
	        ex.printStackTrace();
	    }
	    
	    return null;
	}
}
